package cn.wolfcode.luowowo.webSite.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    /**
     * 添加cookie
     * @param response
     * @param name
     * @param value
     * @param timeOut
     */
    public static void addCookie(HttpServletResponse response, String name, String value, int timeOut) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");  //表示所有请求都会带上cookie,解决跨域和路径问题
        cookie.setMaxAge(timeOut); //设置cookie在浏览器里的存活时间
        response.addCookie(cookie); //把cookie响应回去浏览器
    }

    //从cookie里面取出token
    public static String getToken(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
